package com.kh.statistics.video.core.statistics;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.kh.statistics.video.constant.PlatformConstant;
import com.kh.statistics.video.core.MediaContext;
import com.kh.statistics.video.core.Platform;
import com.kh.statistics.video.entity.ShiPinHaoStatisticsOne;
import com.kh.statistics.video.entity.StatisticsInfo;
import com.kh.statistics.video.entity.StatisticsMeta;
import com.kh.statistics.video.helper.ExcelHelper;
import com.kh.statistics.video.helper.StatisticsHttpHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;

import java.util.*;

/**
 * @BelongsProject: statistics
 * @BelongsPackage: com.kh.statistics.video.core.statistics
 * @Author: Hong.Kong
 * @CreateTime: 2024-05-10  09:39
 * @Description: TODO
 * @Version: 1.0
 */
@Component
@Slf4j
public class ShiPinHaoPlatform implements Platform {
    @Override
    public String support() {
        return PlatformConstant.SHI_PIN_HAO;
    }

    @Override
    public List<StatisticsInfo> getInfo(StatisticsMeta statisticsMeta) {
        return null;
    }

    @Override
    public void statistics(List<StatisticsMeta> list) {
        List<StatisticsInfo> statisticsInfoListAll = new ArrayList<>();
        for (StatisticsMeta statisticsMeta : list) {
            StatisticsInfo statisticsInfo = new StatisticsInfo();
            if ("keyMetrics".equals(statisticsMeta.getName())) {
                keyMetricsStatistics(statisticsInfo, statisticsMeta);
            }
            statisticsInfoListAll.add(statisticsInfo);
        }
        ExcelHelper.export(ExcelHelper.getExcelName(list.get(0).getAccountName(), "视频号统计总"), statisticsInfoListAll, StatisticsInfo.class);
    }

    @Override
    public void oneStatistics(List<StatisticsMeta> statisticsMetaList, MediaContext mediaContext) {
        List<ShiPinHaoStatisticsOne> statisticsInfoListAll = new ArrayList<>();
        for (StatisticsMeta statisticsMeta : statisticsMetaList) {
            String body = StatisticsHttpHelper.request(statisticsMeta);
            if (!handlerResponse(body)) {
                return;
            }
            List<ShiPinHaoStatisticsOne> statisticsInfos = oneStatistics(body);
            statisticsInfoListAll.addAll(statisticsInfos);
            statisticsInfoListAll.forEach((item) -> {
                StatisticsMeta shortUrlReq = new StatisticsMeta();
                shortUrlReq.setUrl("https://channels.weixin.qq.com/cgi-bin/mmfinderassistant-bin/post/get_object_short_link");
                shortUrlReq.setRequestType("post");
                Map<String, Object> params = new HashMap<>();
                params.put("exportId", item.getExportId());
                params.put("nonceId", item.getNonceId());
                params.put("scene", 40);
                params.put("timestamp", System.currentTimeMillis());
                params.put("_log_finder_uin", "");
                params.put("_log_finder_id", "v2_060000231003b20faec8cae3801cc3d3cd01e83cb0777cd2e4cff4b98a8148def3ff3ba41364@finder");
                params.put("reqScene", 7);
                shortUrlReq.setParams(params);
                shortUrlReq.setHeaders(statisticsMetaList.get(0).getHeaders());
                String shortBody = StatisticsHttpHelper.request(shortUrlReq);
                String shorUrl = handlerShorUrl(shortBody);
                item.setLink(shorUrl);
            });
        }


        ExcelHelper.export(ExcelHelper.getExcelName(statisticsMetaList.get(0).getAccountName(), "视频号单条统计"), statisticsInfoListAll, ShiPinHaoStatisticsOne.class);
    }

    private String handlerShorUrl(String body) {
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONObject dataObject = jsonObject.getJSONObject("data");
        return dataObject.getString("shortUrl");
    }

    @Override
    public boolean handlerResponse(String body) {
        return true;
    }

    private List<ShiPinHaoStatisticsOne> oneStatistics(String body) {
        List<ShiPinHaoStatisticsOne> itemList = new ArrayList<>();
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONObject dataObject = jsonObject.getJSONObject("data");
        JSONArray array = dataObject.getJSONArray("list");
        for (Object o : array) {
            ShiPinHaoStatisticsOne statisticsOne = new ShiPinHaoStatisticsOne();
            JSONObject item = (JSONObject) o;
            JSONObject desc = item.getJSONObject("desc");
            JSONArray media = desc.getJSONArray("media");
            if (null != media && media.size() > 0) {
                JSONObject descInfo = (JSONObject) media.get(0);
                String url = descInfo.getString("url");
                statisticsOne.setLink(url);
            }
            String title = desc.getString("description");
            statisticsOne.setWorks(title);
            Long createTime = item.getLong("createTime");
            statisticsOne.setPushDate(DateUtil.format(new Date(createTime * 1000), "yyyy/MM/dd"));
            Long readCount = item.getLong("readCount");
            statisticsOne.setExposure(readCount);
            Long likeCount = item.getLong("likeCount");
            statisticsOne.setLikeCount(likeCount);
            Long favCount = item.getLong("favCount");
            statisticsOne.setClicksNumber(favCount);
            Double fullPlayRate = item.getDouble("fullPlayRate");
            statisticsOne.setFullPlayRate(fullPlayRate);
            Long commentCount = item.getLong("commentCount");
            statisticsOne.setCommentsNumber(commentCount);
            String objectNonce = item.getString("objectNonce");
            statisticsOne.setNonceId(objectNonce);
            String exportId = item.getString("exportId");
            statisticsOne.setExportId(exportId);
            itemList.add(statisticsOne);
        }
        return itemList;
    }

    private void keyMetricsStatistics(StatisticsInfo statisticsInfo, StatisticsMeta statisticsMeta) {
        String body = StatisticsHttpHelper.request(statisticsMeta);
        JSONObject jsonObject = JSONObject.parseObject(body);
        JSONObject data = jsonObject.getJSONObject("data");
        JSONObject totalData = data.getJSONObject("totalData");
        statisticsInfo.setPlaysNumber(totalKeyMetricsStatistics("browse", totalData));
        statisticsInfo.setClicksNumber(totalKeyMetricsStatistics("fav", totalData));
//        statisticsInfo.setCommentsNumber(totalKeyMetricsStatistics("comment", totalData));
    }

    private long totalKeyMetricsStatistics(String type, JSONObject totalData) {
        JSONArray jsonArray = totalData.getJSONArray(type);
        return jsonArray.stream().map(o -> (Integer) o).count();
    }
}
